﻿using System;

using HsTec.Mobile.Green.Util;
using HsTec.Mobile.Green.BLL;
using Baimasoft.Manage.SqlServerDAL;
using System.Web;
using System.IO;
using System.Collections.Generic;

public partial class ReportAnalysis_ImportReport : System.Web.UI.Page
{
    ReportAnalysisBLL bll = new ReportAnalysisBLL();
    Param MyP = new Param();

    protected void Page_Load(object sender, EventArgs e)
    {
        if ((string)Session["Baimasoft_Pers_ID"] == null)
        {
            Response.Redirect("../Logon.aspx");
        }
        string jscript = "function UploadComplete(){";
        jscript += string.Format("__doPostBack('{0}','');", LinkButton1.ClientID.Replace("_", "$"));
        jscript += "};";
        Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "FileCompleteUpload", jscript, true);
        if (!IsPostBack)
        {
            BindsltArea();
            //txtYearsDataBind();
        }
    }
    protected void btn_Statistics_ServerClick(object sender, EventArgs e)
    {
        if (String.IsNullOrEmpty(sltArea.Value.Trim()))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择导入地区！');</script>");
            return;
        }
        if (String.IsNullOrEmpty(sltYear.Value + sltMonth.Value))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('请选择导入年月！');</script>");
            return;
        }
        string sUpLoadDate = sltYear.Value + sltMonth.Value;
        //1.验证是否是通过下划线分割的文件名
        string[] sFileName = FU_Statistics.FileName.Split('_');
        //if (sFileName.Length != 3)
        //{
        //    ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('入库的文件名不符要求！（如：" + Util.GetChineseSpell(sltArea.Items[sltArea.SelectedIndex].Text.Trim()) + "01" + sUpLoadDate.Substring(0, 2) + ".xls）');</script>");
        //    return;
        //}
        string sCity = Util.GetChineseSpell(sltArea.Items[sltArea.SelectedIndex].Text.Trim());
        sCity = sCity.Substring(0, sCity.Length - 1);
        //2.验证上传文件名
        if (!ValidateHelper.ValidateFileName(FU_Statistics.FileName, sCity, sUpLoadDate.Substring(2, sUpLoadDate.Length - 2)))
        {
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('入库的文件名不符要求！（如：" + sCity + "01" + sUpLoadDate.Substring(2, sUpLoadDate.Length - 2) + ".xls）');</script>");
            return;
        }
        //3.验证上传文件类型
        string UpfileExt = System.IO.Path.GetExtension(FU_Statistics.FileName);
        if (UpfileExt != ".xls")
        {
            Text_Confirm_Upstate.Text = "入库的文件名类型不符要求！（必须是EXCEL文件）";
            return;
        }
        //4.验证数据是否已经上传
        //4.1 上传文件
        switch (Util.Upload_File(FU_Statistics, FU_Statistics.FileName, "01"))
        {
            case 1:
                Text_Confirm_Upstate.Text = "上传文件成功！";
                break;
            case 0:
                Text_Confirm_Upstate.Text = "上传文件失败！";
                return;
        }
        //4.2 导入到DataSet中
        Text_Confirm_Upstate.Text = String.Empty;
        ExcelHelper ehelper = new ExcelHelper();
        ehelper.insertTableName = "tb_ReportAnalysis";
        ehelper.excelPath = "01\\" + FU_Statistics.FileName;
        //ehelper.sheetName = "表1 绿色行动计划专项统计表";
        int iNull = 0;
        string sRtn = String.Empty;
        Text_Confirm_Upstate.Text = ehelper.importImportReport(sltArea.Value.Trim(), sUpLoadDate, Session["Baimasoft_Pers_ID"].ToString(), sltYear.Value, ref iNull, ref sRtn);
        //4.3 数据中含有空数据
        if (iNull > 0 && Text_Confirm_Upstate.Text == "导入成功！")
            ClientScript.RegisterStartupScript(this.GetType(), "", "<script>alert('导入EXCEL表中包含空数据请注意补空！');</script>");
        //4.4 数据中含有格式不正确的数据
        if (!String.IsNullOrEmpty(sRtn))
        {
            string tmp = String.Empty;
            string[] sAry = sRtn.Remove(sRtn.Length - 1).Split(',');
            for (int i = 0; i < sAry.Length; i++)
            {
                string[] sArytmp = sAry[i].Split('|');
                Text_Confirm_Upstate.Text += "<BR>(" + (i + 1) + ")数据表中<span style=\"color: #ff0000\">" + sArytmp[0] + "</span>数据项应输入<span style=\"color: #ff0000\">" + sArytmp[1] + "</span>！";
            }
        }
        Util.Delete_File(FU_Statistics.FileName, "01");
    }
    private void BindsltArea()
    {
        sltArea.DataTextField = "Name";
        sltArea.DataValueField = "ID";
        sltArea.DataSource = bll.GetAreaList();
        sltArea.DataBind();
        sltArea.Items.Insert(0, "请选择县市区域...");
        sltArea.Items[0].Value = "";
    }
    //private void txtYearsDataBind()
    //{
    //    txtYears.DataTextField = "Name";
    //    txtYears.DataValueField = "Name";
    //    txtYears.DataSource = MyP.GetCodeByParentCode("1");
    //    txtYears.DataBind();
    //    txtYears.Items.Insert(0, "请选择...");
    //    txtYears.Items[0].Value = "";
    //}
    protected string GetFlashVars()
    {
        return "?" + Server.UrlEncode("id=" + Session["Baimasoft_Pers_ID"].ToString());
    }
    protected void LinkButton1_Click(object sender, EventArgs e)
    {
        Text_Confirm_Upstate.Text = String.Empty;
        List<FileInfo> list = new List<FileInfo>();
        DirectoryInfo di = new DirectoryInfo(Util.ServerPath + "01");
        FileInfo[] info = di.GetFiles("*.xls");
        for (int i = 0; i < info.Length; i++)
        {
            list.Add(info[i]);
        }
        //批量上传
        ExcelHelper ehelper = new ExcelHelper();
        foreach (FileInfo file in list)
        {
            try
            {
                ehelper.insertTableName = "tb_ReportAnalysis";
                ehelper.excelPath = "01\\" + file.Name;
                ehelper.sheetName = String.Empty;
                int iNull = 0;
                string sRtn = String.Empty;
                string sYears = "20" + file.Name.Substring(file.Name.IndexOf("01") + 2, 4);
                string sArea = SQLHelper.ExecuteString("select ID from Area where PinYin='" + file.Name.Substring(0, file.Name.IndexOf("01")) + "'");
                if (!String.IsNullOrEmpty(sArea))
                {
                    Text_Confirm_Upstate.Text += file.Name + ehelper.importImportReport(sArea, sYears, Session["Baimasoft_Pers_ID"].ToString(), sYears.Substring(0, 4), ref iNull, ref sRtn) + "<BR>";
                    //4.3 数据中含有空数据
                    if (iNull > 0 && Text_Confirm_Upstate.Text == "导入成功！")
                        Text_Confirm_Upstate.Text += file.Name + "表中包含空数据请注意补空<BR>";
                    //4.4 数据中含有格式不正确的数据
                    if (!String.IsNullOrEmpty(sRtn))
                    {
                        string tmp = String.Empty;
                        string[] sAry = sRtn.Remove(sRtn.Length - 1).Split(',');
                        for (int i = 0; i < sAry.Length; i++)
                        {
                            string[] sArytmp = sAry[i].Split('|');
                            Text_Confirm_Upstate.Text += "(" + (i + 1) + ")数据表中<span style=\"color: #ff0000\">" + sArytmp[0] + "</span>数据项应输入<span style=\"color: #ff0000\">" + sArytmp[1] + "</span>！<BR>";
                        }
                    }
                    file.Delete();
                }
                else
                {
                    Text_Confirm_Upstate.Text += file.Name.Substring(0, file.Name.IndexOf("01")) + "拼音简写对应的城市不存在！<BR>";
                }
            }
            catch
            {
                break;
            }
        }
        di = new DirectoryInfo(Util.ServerPath + "01");
        info = di.GetFiles("*.xls");
        for (int i = 0; i < info.Length; i++)
        {
            info[i].Delete();
        }
    }
}
